package cn.samler.shopapi.Utils;

import cn.samler.shopapi.Config.IdentifierConfig;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component
public class OrderNoGenerator {
    private static Integer counter = 1;
    private static final Integer MAX_COUNT = 99999;
    private static Long lastTimeStamp = -1L;
    private static OrderNoGenerator ins;
    private final IdentifierConfig config;

    private OrderNoGenerator(IdentifierConfig config) {
        this.config = config;
    }

    @PostConstruct
    private void init() {
        ins = new OrderNoGenerator(this.config);
    }

    public static OrderNoGenerator getInstance() {
        return ins;
    }

    public synchronized String create() {
        Long currentTimeStamp = System.currentTimeMillis();
        if (currentTimeStamp == lastTimeStamp)
            counter = (counter + 1) & MAX_COUNT;
        if (counter == 0) {
            while (lastTimeStamp >= System.currentTimeMillis())
                lastTimeStamp = System.currentTimeMillis();
        } else {
            lastTimeStamp = currentTimeStamp;
            counter = 1;
        }

        StringBuilder orderNo = new StringBuilder();
        orderNo.append("P0");
        orderNo.append(String.format("%02d", config.getDatacenterId()));
        orderNo.append(String.format("%03d", config.getMachineId()));
        orderNo.append(currentTimeStamp);
        orderNo.append(String.format("%05d", counter++));

        return orderNo.toString();
    }
}
